package 动态数组.栈;

import 动态数组.队列.ArrayQueue;

/**
 * 队列实现栈
 */
public class QueueToStack {
    public static void main(String[] args) {
        StackImplByQueue<Integer> stack = new StackImplByQueue<>();
        for (int i = 1; i <= 4; i++) {
            stack.push(i);
        }
        System.out.println(stack);
        System.out.println(stack.poll());
        stack.push(5);
        System.out.println(stack);
    }
}
class StackImplByQueue<E> {
    private ArrayQueue<E> queueA;
    private ArrayQueue<E> queueB;

    public StackImplByQueue(){
        queueA = new ArrayQueue<>();
        queueB = new ArrayQueue<>();
    }

    public void push(E e){
        if (queueA.isEmpty() && queueB.isEmpty()){
            queueA.offer(e);
        }else if (queueA.isEmpty()){
            queueB.offer(e);
        }else {
            queueA.offer(e);
        }
    }

    public E poll(){
        if (!queueA.isEmpty()){
            while (queueA.size() != 1){
                queueB.offer(queueA.poll());
            }
            return queueA.poll();
        }else {
            while (queueB.size() != 1){
                queueA.offer(queueB.poll());
            }
            return queueB.poll();
        }
    }

    public E peek(){
        if (!queueA.isEmpty()){
            while (queueA.size() != 1){
                queueB.offer(queueA.poll());
            }
            E ret = queueA.poll();
            queueB.offer(ret);
            return ret;
        }else {
            while (queueB.size() != 1){
                queueA.offer(queueB.poll());
            }
            E ret = queueB.poll();
            queueA.offer(ret);
            return ret;
        }

    }

    @Override
    public String toString() {
        if (queueA.isEmpty() && queueB.isEmpty()){
            return "[]";
        }else if (queueA.isEmpty()){
            return queueB.toString();
        }else {
            return queueA.toString();
        }
    }
}
